<?php


//验证 是否为空
function is_empty($value){
    if(!isset($value) || empty($value)) return true;
    return false;
}
//验证 字符串长度
function is_len($str, $len=0, $type='>'){
    if(!isset($str)) return false;
    $str_len = iconv_strlen($str,"UTF-8");
    if($type == '>' && $str_len>$len)  return true;
    if($type == '=' && $str_len==$len) return true;
    if($type == '<' && $str_len<$len)  return true;
    return false;
}

//负数取0
function to_positive($num){
    $num = floatval($num);
    if($num<0) return 0;
    return $num;
}


//生成用户TOKEN
function user_token(){
    return md5(uniqid(microtime(true),true).rand(100000,999999));
}
//生成订单号
function order_sn() {
    // $order_no = date('YmdHis'). substr(microtime(), 2, 5) . sprintf('%02d', rand(100000, 999999));
    // $order_no = date('ymdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
  return date('ymdHis').str_pad(mt_rand(1, 99999999), 8, '0', STR_PAD_LEFT);
}
//生成固定长度字符串
function rand_str($length=6, $type='num')   
{   
    $key = '';
    $pattern = '0123456789';
    if($type == 'char') $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
    if($type == 'lowerchar') $pattern = '1234567890abcdefghijklmnopqrstuvwxyz';  
    for($i=0;$i<$length;$i++) $key .= $pattern{mt_rand(0, iconv_strlen($pattern,"UTF-8")-1)};    //生成php随机数  
    return $key;   
}
//随机生成国内ip
function rand_ip(){
    $ip_long = array(
        array('607649792', '608174079'),
        array('1038614528', '1039007743'),
        array('1783627776', '1784676351'),
        array('2035023872', '2035154943'),
        array('2078801920', '2079064063'),
        array('-1950089216', '-1948778497'),
        array('-1425539072', '-1425014785'),
        array('-1236271104', '-1235419137'),
        array('-770113536', '-768606209'),
        array('-569376768', '-564133889'),
    );
    $rand_key = mt_rand(0, 9);
    return $ip = long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));
}

//检查url是否能请求
function url_exists($url)
{
    $arr = get_headers($url,1);
    if(preg_match('/200/',$arr[0])){
        return true;
    }else{
        return false;
    }
}
//短链生成
function short_url($long_url, $type='sina'){
    /*
    木子短链
    http://muzidwz.cn/sina_short.php?data=http://www.baidu.com
    http://muzidwz.cn/tencent.jason?data=http://www.baidu.com
    蓝鸟短链
    http://lnurl.cn/sina/short-api?url_long=http://www.baidu.com
    http://lnurl.cn/weixin/short-api?url_long=http://www.baidu.com
    冷狗短链
    http://dogdwz.cn/tcnjson?url_long=http://www.baidu.com
    http://dogdwz.cn/txjson?url_long=http://www.baidu.com
     */
    if($type == 'sina')   $api_url = "http://dogdwz.cn/tcnjson?url_long=".$long_url;
    if($type == 'wechat') $api_url = "http://dogdwz.cn/txjson?url_long=".$long_url;

    $rs = curl_hack($api_url);
    return $rs;
}
//微信安全域名检测
function wechat_check_safe($url){
    $api_url = "http://www.xiaohejc.cn/check_api.php?url_long={$url}";
    $rs = file_get_contents($api_url);
    //$rs = curl_hack($api_url);
    return $rs;
}
//银行卡号检测
function bankno_check($bankNo=''){
    $url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?cardNo={$bankNo}&cardBinCheck=true";
    $rs = curl_hack($url);
    $rs = json_decode($rs, true);
    if($rs['validated'] == false) return false;
    return ['bank'=>strtolower($rs['bank'])];
}


/**
* 简单对称加密算法之加密
* @param String $string 需要加密的字串
* @param String $skey 加密EKY
* @return String
*/
function to_encode($string = '', $skey = 'bt18a9X01Dt') {
    $strArr = str_split(base64_encode($string));
    $strCount = count($strArr);
    foreach (str_split($skey) as $key => $value)
    $key < $strCount && $strArr[$key].=$value;
    return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
}
/**
* 简单对称加密算法之解密
* @param String $string 需要解密的字串
* @param String $skey 解密KEY
* @return String
*/
function to_decode($string = '', $skey = 'bt18a9X01Dt') {
    $strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
    $strCount = count($strArr);
    foreach (str_split($skey) as $key => $value)
    $key <= $strCount && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
    return base64_decode(join('', $strArr));
}

//成功 JSON格式化返回
function json_ok($info, $data = [], $code = 1)
{
    cross_domain();
    $result = ['code' => $code, 'info' => $info, 'data' => $data];
    throw new \think\exception\HttpResponseException(json($result));
    //return json($result);
}
//失败 JSON格式化返回
function json_err($info, $data = [], $code = -1)
{
    cross_domain();
    $result = ['code' => $code, 'info' => $info, 'data' => $data];
    throw new \think\exception\HttpResponseException(json($result));
    //return json($result);
}
function cross_domain(){
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
    header('Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS,PATCH');
    return true;
}

//curl获取内容
function curl_hack($url){
    $ch2 = curl_init();
    $user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";//模拟windows用户正常访问
    curl_setopt($ch2, CURLOPT_URL, $url);
    curl_setopt($ch2, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch2, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:'.rand_ip(), 'CLIENT-IP:'.rand_ip()));
    //追踪返回302状态码，继续抓取
    // curl_setopt($ch2, CURLOPT_HEADER, true); 
    curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, true);

    curl_setopt($ch2, CURLOPT_NOBODY, false);
    curl_setopt($ch2, CURLOPT_REFERER, 'http://'.rand_ip());//模拟来路
    curl_setopt($ch2, CURLOPT_USERAGENT, $user_agent);
    $temp = curl_exec($ch2);
    curl_close($ch2);
    return $temp;
}

//时间函数
function for_timestamp($type='day'){
    //php获取今日开始时间戳和结束时间戳
    if($type == 'day'){
        $start = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $end   = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
    }
    //php获取昨日起始时间戳和结束时间戳
    if($type == 'yesterday'){
        $start = mktime(0,0,0,date('m'),date('d')-1,date('Y'));
        $end   = mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
    }
    //php获取本周起始时间
    if($type == 'week'){
        $start = mktime(0,0,0,date("m"),date("d")-date("w")+1,date("Y"));
        $end   = mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y"));
    }
    //php获取上周起始时间戳和结束时间戳
    if($type == 'lastweek'){
        $start = mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'));
        $end   = mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'));
    }
    //php获取本月起始时间戳和结束时间戳
    if($type == 'month'){
        $start = mktime(0,0,0,date('m'),1,date('Y'));
        $end   = mktime(23,59,59,date('m'),date('t'),date('Y'));
    }
    //php获取本年起始时间戳和结束时间戳
    if($type == 'year'){
        $start = mktime(0,0,0,1,1,date('Y'));
        $end   = mktime(23,59,59,12,30,date('Y'));
    }
    return ['start'=>$start, 'end'=>$end];
}


/*----- 常用函数 start -----*/

//记录日志
function log_to($msg, $file='all', $level=1){
    $cls = new App\Think\Log();
    $msg = is_array($msg) ? json_encode($msg, JSON_UNESCAPED_UNICODE) : $msg;
    return $cls->log($msg, $level, $file);
}

//返回语言
function __($lang){
    return $lang;
}

//获取数据库对象
function db($table){
    return \App\Think\Db::name($table);
}

//缓存快捷方法
function cache($name, $value='', $expire=null){
    // $rdb = \App\Think\Redis::init();
    if(empty($value)) return \App\Think\Cache::get($name);
    return \App\Think\Cache::set($name, $value, $expire);
}
/*----- 常用函数 end -----*/


/**
 * 数据库操作快捷方法 --- start --- //
 */

//获取单个字段信息
function db_get_field($table, $where, $field='id'){
    return db($table)->where($where)->value($field);
}
//获取单行记录
function db_get_row($table, $where){
    return db($table)->where($where)->find();
}
//获取多行记录
function db_get_all($table, $where){
    return db($table)->where($where)->select();
}
//插入单行记录
function db_add($table, $data){
    $_insertId = db($table)->insertGetId($data);
    return $_insertId;
}
//插入记录,存在则替换
//demo: db_replace_all('fa_ttt', ['admin_id'=>1, 'cat_id'=>1], ['updatetime'=>time()]);
function db_replace_row($table, $insert_data, $update_data){
    if(!is_array($insert_data) || count($insert_data)<=0) return false;
    $field_str = $value_str = $update_field_str = [];
    foreach($insert_data as $k=>$v){
        $field_str[] = $k;
        $value_str[] = "'$v'";
    }
    $field_str = implode(',', $field_str);
    $value_str = implode(',', $value_str);
    foreach($update_data as $k=>$v){
        $update_field_str[] = "$k='{$v}'";
    }
    $update_field_str = implode(',', $update_field_str);
    $sql = "INSERT INTO {$table}({$field_str})"." VALUE({$value_str}) "." ON DUPLICATE KEY UPDATE {$update_field_str}";
    return db()->execute($sql);
}
//插入多行记录,存在则替换
//demo: db_replace_all('fa_ttt',[['admin_id'=>1, 'cat_id'=>1],['admin_id'=>2, 'cat_id'=>2],], ['updatetime']);
function db_replace_all($table, $insert_data, $update_data){
    if(!is_array($insert_data) || count($insert_data)<=0) return false;
    $field_str = $value_str = $update_field_str = '';
    foreach($insert_data as $k=>$v){
        $field_str = implode(',',  array_keys($v) );
        $value_str .= "(".implode(',',  array_values($v) )."),";
    }
    $value_str = rtrim($value_str, ',');
    foreach($update_data as $kk=>$vv){
      $update_field_str .= "$vv=values($vv),";
    }
    $update_field_str = rtrim($update_field_str, ',');
    $sql = "INSERT INTO {$table}({$field_str})"." VALUES {$value_str} "." ON DUPLICATE KEY UPDATE {$update_field_str}";
    return db()->execute($sql);
}
//插入记录,存在则不插入
//demo: db_replace_all('fa_ttt', ['admin_id'=>1, 'cat_id'=>1], ['updatetime'=>time()]);
function db_insert_or($table, $insert_data, $update_data){
    if(!is_array($insert_data) || count($insert_data)<=0) return false;
    $field_str = $value_str = $update_field_str = $update_value_str = [];
    foreach($insert_data as $k=>$v){
        $field_str[] = $k;
        $value_str[] = "'$v'";
    }
    $field_str = implode(',', $field_str);
    $value_str = implode(',', $value_str);
    foreach($update_data as $k=>$v){
        $update_field_str[] = "$k";
        $update_value_str[] = " AND $k='{$v}' ";
    }
    $update_field_str = implode(',', $update_field_str);
    $update_value_str = implode('', $update_value_str);
    $sql = "INSERT INTO {$table}($field_str) SELECT {$value_str} FROM DUAL ".
           "WHERE NOT EXISTS(SELECT {$update_field_str} FROM {$table} WHERE 1 {$update_value_str})";
    return db()->execute($sql);
}
//插入多行记录
function db_add_all($table, $data){
    return db($table)->data($data)->insertAll();
}
//更新单行记录
function db_edit($table, $data, $where){
    return db($table)->where($where)->update($data);
}
//字段增加
function db_field_inc($table, $where, $field='', $num=1){
    $num = $num >= 0 ? "+{$num}" : "{$num}";
    db($table)->where($where)->setInc($field, $num);
    return true;
}
//生成where in条件
function db_where_in($field, $items){
    if(is_array($items)){
        // $where_str = !empty($items) ? implode(',', $items) : "''";
        $where_str = !empty($items) ? "'".join("','", array_values($items) )."'" : "''"; 
        return $field." IN($where_str) ";
    }
    $where_str = !empty($items) ? $items : "''";
    return $field." IN($where_str) ";
}
//------ end ------ //

/**
 * 数组操作快捷方法 --- start --- //
 */
function arr_all($arr, $key, $val){
    $res = [];
    foreach ($arr as $k => $v) {
        if($v[$key] == $val) $res[] = $v;
    }
    return $res;
}
function arr_row($arr, $key, $val){
    $res = [];
    foreach ($arr as $k => $v) {
        if($v[$key] == $val) return $v;
    }
    return $res;
}
function arr_field($arr, $key, $val, $field=''){
    foreach ($arr as $k => $v) {
        if( $v[$key] == $val && isset($v[$field]) ) return $v[$field];
    }
    return '';
}
//------ end ------ //



/**
 * 相关业务/配置 --- start --- //
 */

function banner_list(){
    return \App\Think\Config::get('Project.banner');
}
//平台类型
function platform_type(){
    return \App\Think\Config::get('Project.plat_type');
}
//平台列表
function platform_list(){
    return \App\Think\Config::get('Project.plat_list');
}
//检测平台的状态(是否关闭)
function check_platform_status($val){
    $list = platform_list();
    $row  = arr_row($list, 'key', $val);
    if(@$row['status'] == 1) return true;
    return false;
}
//获取平台信息
function platform_name($key, $field='name'){
    $list = platform_list();
    $row  = arr_row($list, 'key', $key);
    return isset($row[$field]) ? $row[$field] : '';
}

//头像列表
function avatar_list(){
    return \App\Think\Config::get('Project.avatar');
}

//支付方式
function payment_list(){
    return \App\Think\Config::get('Project.payment');
}
//银行卡列表
function bank_list(){
    return \App\Think\Config::get('Project.bank');
}

//获取红利说明
function bonus_name($key, $field='name'){
    $list = \App\Think\Config::get('Project.bonus');
    $row  = arr_row($list, 'key', $key);
    return isset($row[$field]) ? $row[$field] : '';
}
//------ end ------ //

